package com.eshop.modules.system.rest;

import com.eshop.modules.system.service.dto.UserDto;
import java.util.Collection;
import java.util.Collections;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.function.Function;
import com.eshop.modules.system.service.dto.RoleSmallDto;
import com.eshop.utils.SecurityUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import java.util.Iterator;
import java.util.Set;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.PostMapping;
import com.eshop.modules.aop.ForbidSubmit;
import com.eshop.exception.BadRequestException;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.validation.annotation.Validated;
import com.eshop.modules.system.domain.Role;
import cn.hutool.core.lang.Dict;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.data.domain.Pageable;
import com.eshop.logging.aop.log.Log;
import java.io.IOException;
import java.util.List;
import com.eshop.modules.system.service.dto.RoleDto;
import com.eshop.modules.system.service.dto.RoleQueryCriteria;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import com.eshop.dozer.service.IGenerator;
import com.eshop.modules.system.service.UserService;
import com.eshop.modules.system.service.RoleService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;

@Api(tags = { "系统：角色管理" })
@RestController
@RequestMapping({ "/api/roles" })
public class RoleController
{
    private final RoleService roleService;
    private final UserService userService;
    private final IGenerator generator;
    private static final String ENTITY_NAME = "role";
    
    public RoleController(final RoleService roleService, final UserService userService, final IGenerator generator) {
        this.roleService = roleService;
        this.userService = userService;
        this.generator = generator;
    }
    
    @ApiOperation("获取单个role")
    @GetMapping({ "/{id}" })
    @PreAuthorize("@el.check('roles:list')")
    public ResponseEntity<Object> getRoles(@PathVariable final Long id) {
        return new ResponseEntity(this.roleService.findById(id), HttpStatus.OK);
    }
    
    @Log("导出角色数据")
    @ApiOperation("导出角色数据")
    @GetMapping({ "/download" })
    @PreAuthorize("@el.check('role:list')")
    public void download(final HttpServletResponse response, final RoleQueryCriteria criteria) throws IOException {
        this.roleService.download(this.generator.convert((List)this.roleService.queryAll(criteria), (Class)RoleDto.class), response);
    }
    
    @ApiOperation("返回全部的角色")
    @GetMapping({ "/all" })
    @PreAuthorize("@el.check('roles:list','user:add','user:edit')")
    public ResponseEntity<Object> getAll(final RoleQueryCriteria criteria, @PageableDefault(value = 2000, sort = { "level" }, direction = Sort.Direction.ASC) final Pageable pageable) {
        return new ResponseEntity(this.roleService.queryAlls(criteria, pageable), HttpStatus.OK);
    }
    
    @Log("查询角色")
    @ApiOperation("查询角色")
    @GetMapping
    @PreAuthorize("@el.check('roles:list')")
    public ResponseEntity<Object> getRoles(final RoleQueryCriteria criteria, final Pageable pageable) {
        return new ResponseEntity(this.roleService.queryAll(criteria, pageable), HttpStatus.OK);
    }
    
    @ApiOperation("获取用户级别")
    @GetMapping({ "/level" })
    public ResponseEntity<Object> getLevel() {
        return new ResponseEntity(Dict.create().set("level", this.getLevels(null)), HttpStatus.OK);
    }
    
    @ForbidSubmit
    @Log("新增角色")
    @ApiOperation("新增角色")
    @PostMapping
    @PreAuthorize("@el.check('roles:add')")
    public ResponseEntity<Object> create(@Validated @RequestBody final Role resources) {
        if (resources.getId() != null) {
            throw new BadRequestException("A new role cannot already have an ID");
        }
        this.getLevels(resources.getLevel());
        return new ResponseEntity(this.roleService.create(resources), HttpStatus.CREATED);
    }
    
    @ForbidSubmit
    @Log("修改角色")
    @ApiOperation("修改角色")
    @PutMapping
    @PreAuthorize("@el.check('roles:edit')")
    public ResponseEntity<Object> update(@Validated @RequestBody final Role resources) {
        this.getLevels(resources.getLevel());
        this.roleService.update(resources);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }
    
    @ForbidSubmit
    @Log("修改角色菜单")
    @ApiOperation("修改角色菜单")
    @PutMapping({ "/menu" })
    @PreAuthorize("@el.check('roles:edit')")
    public ResponseEntity<Object> updateMenu(@RequestBody final Role resources) {
        final RoleDto role = this.roleService.findById(resources.getId());
        this.getLevels(role.getLevel());
        this.roleService.updateMenu(resources, role);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }
    
    @ForbidSubmit
    @Log("删除角色")
    @ApiOperation("删除角色")
    @DeleteMapping
    @PreAuthorize("@el.check('roles:del')")
    public ResponseEntity<Object> delete(@RequestBody final Set<Long> ids) {
        for (final Long id : ids) {
            final RoleDto role = this.roleService.findById(id);
            this.getLevels(role.getLevel());
        }
        try {
            this.roleService.delete(ids);
        }
        catch (Throwable e) {
            throw new BadRequestException("所选角色存在用户关联，请取消关联后再试");
        }
        return new ResponseEntity(HttpStatus.OK);
    }
    
    private int getLevels(final Integer level) {
        final UserDto user = this.userService.findByName(SecurityUtils.getUsername());
        final List<Integer> levels = this.roleService.findByUsersId(user.getId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList());
        final int min = Collections.min(levels);
        if (level != null && level < min) {
            throw new BadRequestException("权限不足，你的角色级别：" + min + "，低于操作的角色级别：" + level);
        }
        return min;
    }
}
